<template>
	<div>
		<el-tabs v-model="activeName" @tab-change="handleTabsClick">
			<el-tab-pane v-for="(item, index) in tabList" :key="index" :label="item.label" :name="item.value"> </el-tab-pane>
			<div class="btn tr w-100" id="no-print">
				<el-button v-if="isShowPint" type="primary" @click="printHtml('print_area')">打印</el-button>
			</div>
			<component
				id="print_area"
				:key="reloadKey"
				:isDetail="isDetail"
				:params="params"
				v-if="!Loading"
				:is="components[activeName]"
				:editData="editData"
				:otherData="nowRowData"
				:isPigeonhole="isPigeonhole"
				:caseId="caseId"
				:creditCode="creditCode"
				:custome="custome"
				:approvalStatus="approvalStatus"
				:applyNo="nowRowData?.applyNo"
				:editMode="editMode"
        		:activeName="activeName"
				:isOkApproval="isOkApproval"
				@save="onSave"
			></component>
		</el-tabs>
	</div>
</template>

<script setup lang="ts">
import { printHtml } from '@/utils/print'
import { filterEmptyObj } from '@/utils/util'
import { md5 } from '@/utils/encdecrpt'
import apiMod from '@/apiMod'
import { useCommonStore } from '@/stores/common'
import {components} from './components/config'
const { setTempParams, setMoreSearch, setGloabnowRowData } = useCommonStore()

const props = defineProps<{
	list?: any
	creditCode?: string | number
	modelUrl?: string
	nowRowData?: any
	params?: any
	isDetail?: boolean
	custome?: boolean
	approvalStatus?: string | number
	applyNo?: string | number
	isPigeonhole?:boolean
	editMode?:any //五类老人
	isOkApproval?:any //五类老人
}>()

const emit = defineEmits(['refresh-change'])
const belongDate = props.params?.belongDate

const reloadKey = ref(0)
const Loading = ref(true)
const tabList = computed({
	get() {
		let data = []
		if (props.list) {
			data = Array.isArray(props.list) ? props.list : JSON.parse(props.list)
		}
		activeName.value = data[0]?.value
		return data
	},
	set() {},
})

const caseId = ref(null)
const isShowPint = computed(()=> {
  return !['report_1002','bed_report_1003','bed_hl_report_1003','EntryOrgPromise'].includes(activeName.value)
})
const formId = computed({
	get() {
		const str = [props.params?.organizationId, belongDate?.replace('-', '').substring(0, 6), props.params?.subsidyProjectId,props.params.applicateObject||undefined]
			.filter(Boolean)
			.join('_')
		return props.applyNo || props.nowRowData?.applyNo || md5(str)
	},
	set() {},
})

const activeName = ref('ApplyTable')
const editData: any = ref({})

const activeItemObj: any = computed(() => {
	return tabList.value.find((item) => item.value === activeName.value)
})

const getCustomeResult = () => {
	if (!activeItemObj.value) return
	Loading.value = true
	editData.value = {
		...(activeItemObj.value?.result || {}),
	}
	caseId.value = activeItemObj.value.label
	Loading.value = false
}
const resultId: any = ref('')

// 获取数据
const getResult = () => {
	if (!formId.value && !props.applyNo) return
	Loading.value = true

	let query: any = {
		fromId: props.applyNo || formId.value,
		tableTemplateId: activeItemObj.value?.value,
		fromType: activeItemObj.value?.value,
	}
	if (belongDate && props.approvalStatus !==-2) {
		query.applyYear = belongDate.replace('年', '-').replace('月', '').split('-')[0]
		query.applyMonth = belongDate.replace('年', '-').replace('月', '').split('-')[1]
	}
  
	caseId.value = activeItemObj.value?.result || undefined
	if (caseId.value) {
		query.id = caseId.value
	}
	apiMod
		.view_formResults_list(query)
		.then((res) => {
			const moreNews = res.data[0] || {}
			const tempObj = filterEmptyObj(moreNews.dataContent)
      editData.value = tempObj ||{}
      editData.value.formId = formId.value
      editData.value.tableTemplateId = moreNews.tableTemplateId
      editData.value.result_case_id = moreNews.id
      editData.value.dataContent = undefined
			
			resultId.value = moreNews.id
			Loading.value = false
		})
		.catch(() => {
			Loading.value = false
		})
}

const onSave = (model, reportId, dataItem) => {
	if (props.isDetail && !editData.value.formId) return
	const caseId = dataItem?.result_case_id || resultId.value
	let baseApi = caseId ? 'view_formResults_edit' : 'view_formResults_add'

	let query: any = {
		dataContent: model,
		dataResults: model,
		fromId: formId.value,
		fromType: reportId,
		tableTemplateId: reportId,
		projectId: props.params?.subsidyProjectId,
	}
  if(model.idCards) {
    query.idCards = model.idCards
  }
	if (belongDate) {
    const year = belongDate.replace('年', '-').replace('月', '').split('-')[0]
    const month = belongDate.replace('年', '-').replace('月', '').split('-')[1]
		query.applyYear = +year
		query.applyMonth = +(month.charAt('0') ==0?month.replace('0',''):month)
	}
	if (caseId) {
		query.id = caseId
		delete query.fromId
	}
	apiMod[baseApi](query).then((res) => {
		if (!query.id) resultId.value = res.data
		emit('refresh-change', formId.value,props.list)
	})
}

const handleTabsClick = (tabNames?: string) => {
  resultId.value = ''
	Loading.value = true
	if (props.custome) {
		getCustomeResult()
	} else if (props.params) {
		getResult()
	} else {
		setTimeout(() => {
			Loading.value = false
		}, 100)
	}
}
//设置一个打印黑名单，不能显示打印按钮
let isShowPrint = computed(() => {
	let BlackList = [
		'post_apply_promise',
		'post_org_promise',
		'entry_apply_promise',
		'entry_org_promise'
	]
	if(BlackList.includes(activeName.value)){
		return false
	}else{
		return true
	}
})
onMounted(() => {
	handleTabsClick('report_1001')
})

onUnmounted(() => {
	setGloabnowRowData({})
	setMoreSearch({})
	setTempParams({})
})
</script>

<style scoped lang="scss">
:deep(.el-tabs__active-bar) {
	border-radius: 2.5px;
	height: 5px;
	// left: 4%;
	// width: 30px !important;
	background-color: #0052d9;
}
:deep(.el-tabs__item) {
  padding: 0 10px;
}
</style>
